package cn.shopifymall.springTransaction.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;
import org.springframework.transaction.support.TransactionCallbackWithoutResult;
import org.springframework.transaction.support.TransactionTemplate;

/**
 * @Author 孤风雪影
 * @Email gitee.com/efairy520
 * @Date 2023/2/19 14:16
 * @Version 1.0
 */
@Component
public class UserService {
    
    @Autowired
    JdbcTemplate jdbcTemplate;
    
    @Autowired
    PlatformTransactionManager transactionManager;
    
    @Autowired
    TransactionTemplate transactionTemplate;

    public void transfer2() {
        transactionTemplate.execute(new TransactionCallbackWithoutResult() {
            @Override
            protected void doInTransactionWithoutResult(TransactionStatus status) {
                try {
                    jdbcTemplate.update("update user set money = ? where name = ?;", 99, "wangwu");
                    int i = 1/0;
                } catch (DataAccessException e) {
                    e.printStackTrace();
                    // 设置当前事务回滚
                    status.setRollbackOnly();
                }
            }
        });
    }
    
    public void transfer1() {
        //1.定义默认的事务属性
        DefaultTransactionDefinition definition = new DefaultTransactionDefinition();
        //2.获取TransactionStatus
        TransactionStatus status = transactionManager.getTransaction(definition);
        try {
            jdbcTemplate.update("update user set money = ? where name = ?;", 99, "wangwu");
            int i = 1/0;
            transactionManager.commit(status);
        } catch (DataAccessException e) {
            e.printStackTrace();
            //回滚事务
            transactionManager.rollback(status);
        }
    }
}
